// 导入express模块;
const express = require("express");

const router = express.Router();
// 加密解密
const bcryptjs = require("bcryptjs");
const userinfoDB = require("../../schemas/userInfo");

// 登录
router.post("/", async (req, res) => {
  let { username, password } = req.body;
  // 检查格式是否规范
  // 校验用户名正则
  let regUser = /^[u4E00-\u9FA5A-Za-z][\u4E00-\u9FA5A-Za-z0-9]{0,7}$/;
  // 密码至少包含 数字和英文
  let regpass = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;

  if (regUser.test(username) && regpass.test(password)) {
    // 查找数据库是否存在该用户
    let result = await userinfoDB.findOne({ username });
    // console.log(result)

    if (result) {
      // 存在该用户        原始值，加严的值  对比成功就返回true
      const isPasswordSame = bcryptjs.compareSync(password, result.password);
      if (isPasswordSame) {
        // 密码匹配
        req.session.userinfo = {
          username: result.userName,
          admin: result.admin,
          _id: result._id,
          photo: result.photo,
        };

        res.send({
          code: 0,
          txt: '登录成功',
          data: {
            photo: result.photo,
            username:result.userName
          }
        });

      } else {
        // 密码不匹配
        res.send({
          code: 3,
          txt: "密码不正确，请检查后重试",
        });
      }
    } else {
      // 不存在该用户
      res.send({
        code: 2,
        txt: "用户名不存在，先注册",
      });
    }
  } else {
    // 格式有误
    res.send({
      code: 1,
      txt: "格式有误",
    });
  }

  // res.send(data);
});

// 检查登录
router.get('/checkLogin', (req, res) => {
  let userinfo = req.session.userinfo;
  // console.log(req.session);
  if (userinfo) {
    res.send({
      code: 0,
      txt: '已经登录',
      data:userinfo
    })
  } else {
    res.send({
      code: 1,
      txt: '用户未登录',
      data:{}
    })
  }
})

// 退出登录
router.get('/logout', (req, res) => {
  req.session.destroy()
  res.send({code:0,txt:"退出登录成功"})
})

module.exports = router;
